# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-07-15 23:22
# File     : basic_usage.py
# Project  : dynamic-portfolio-optimizer
# Desc     : 基础使用示例

"""
多数据源金融市场数据获取系统使用示例
"""

import os
import sys
from datetime import datetime, timedelta
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.services.market_data_service import MarketDataService
import pandas as pd


def setup_environment():
    """设置环境变量（示例）"""
    # 在实际使用中，建议使用.env文件或环境变量
    os.environ['ALPHA_VANTAGE_API_KEY'] = 'your_alpha_vantage_key'
    os.environ['POLYGON_API_KEY'] = 'your_polygon_key'
    os.environ['FINNHUB_API_KEY'] = 'your_finnhub_key'
    os.environ['TWELVE_DATA_API_KEY'] = 'your_twelve_data_key'
    os.environ['ALPACA_API_KEY'] = 'your_alpaca_key'
    os.environ['ALPACA_SECRET_KEY'] = 'your_alpaca_secret'
    os.environ['NASDAQ_DATA_LINK_API_KEY'] = 'your_nasdaq_key'
    os.environ['MARKETSTACK_API_KEY'] = 'your_marketstack_key'


def main():
    """主函数演示各种功能"""

    print("🚀 初始化金融数据服务...")

    # 设置API密钥（可选）
    setup_environment()

    # 创建服务实例
    market_service = MarketDataService(enable_cache=True)

    # 1. 测试数据源连接
    print("\n📡 测试数据源连接...")
    connections = market_service.test_data_sources()
    for source, status in connections.items():
        status_emoji = "✅" if status else "❌"
        print(f"{status_emoji} {source}: {'连接正常' if status else '连接失败'}")

    # 2. 获取单只股票历史数据
    print("\n📈 获取AAPL历史数据...")
    start_date = datetime.now() - timedelta(days=30)
    end_date = datetime.now()

    aapl_data = market_service.get_stock_price(
        symbols='AAPL',
        start_date=start_date,
        end_date=end_date,
        interval='1d'
    )

    if not aapl_data.empty:
        print(f"✅ 获取到{len(aapl_data)}条AAPL数据")
        print("最近5天数据：")
        print(aapl_data.tail().round(2))

    # 3. 获取多只股票数据
    print("\n📊 获取多只科技股数据...")
    tech_stocks = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'NVDA']

    multi_data = market_service.get_stock_price(
        symbols=tech_stocks,
        start_date=start_date,
        end_date=end_date,
        interval='1d'
    )

    for symbol, data in multi_data.items():
        if not data.empty:
            latest_price = data['close'].iloc[-1]
            print(f"📈 {symbol}: ${latest_price:.2f}")

    # 4. 获取实时报价
    print("\n⚡ 获取实时报价...")
    real_time_quotes = market_service.get_real_time_quote(tech_stocks[:3])

    for symbol, quote in real_time_quotes.items():
        if quote:
            change_emoji = "📈" if quote['change'] > 0 else "📉"
            print(f"{change_emoji} {symbol}: ${quote['price']:.2f} "
                  f"({quote['change']:+.2f}, {quote['change_percent']:+.2f}%)")

    # 5. 获取基本面数据
    print("\n🏢 获取公司基本面数据...")
    fundamentals = market_service.get_company_fundamentals(['AAPL', 'GOOGL'])

    for symbol, data in fundamentals.items():
        if data:
            print(f"\n📋 {symbol} ({data.get('company_name', 'N/A')}):")
            print(f"   行业: {data.get('sector', 'N/A')}")
            print(f"   市值: ${data.get('market_cap', 0):,.0f}")
            print(f"   P/E比: {data.get('pe_ratio', 'N/A')}")
            print(f"   P/B比: {data.get('pb_ratio', 'N/A')}")

    # 6. 获取期权数据（如果支持）
    print("\n🎯 获取AAPL期权数据...")
    try:
        expiration_date = datetime.now() + timedelta(days=30)
        options_data = market_service.get_options_chain('AAPL', expiration_date)

        if not options_data.empty:
            print(f"✅ 获取到{len(options_data)}个期权合约")
            # 显示前5个看涨期权
            calls = options_data[options_data['type'] == 'call'].head()
            if not calls.empty:
                print("前5个看涨期权:")
                print(calls[['strike', 'bid', 'ask', 'volume']].round(2))
        else:
            print("⚠️ 未获取到期权数据")
    except Exception as e:
        print(f"⚠️ 期权数据获取失败: {e}")

    # 7. 获取市场新闻
    print("\n📰 获取市场新闻...")
    news = market_service.get_market_news(['AAPL', 'TSLA'], limit=5)

    for i, article in enumerate(news[:3], 1):
        print(f"\n📄 新闻 {i}: {article.get('title', 'N/A')}")
        print(f"   来源: {article.get('source', 'N/A')}")
        print(f"   时间: {article.get('published_at', 'N/A')}")
        print(f"   链接: {article.get('url', 'N/A')}")

    # 8. 数据分析示例
    print("\n📊 简单数据分析...")
    if not aapl_data.empty:
        # 计算技术指标
        aapl_data['MA5'] = aapl_data['close'].rolling(5).mean()
        aapl_data['MA20'] = aapl_data['close'].rolling(20).mean()
        aapl_data['volatility'] = aapl_data['close'].pct_change().rolling(20).std() * 100

        latest_data = aapl_data.iloc[-1]
        print(f"📈 AAPL技术指标:")
        print(f"   当前价格: ${latest_data['close']:.2f}")
        print(f"   5日均线: ${latest_data['MA5']:.2f}")
        print(f"   20日均线: ${latest_data['MA20']:.2f}")
        print(f"   20日波动率: {latest_data['volatility']:.2f}%")

        # 趋势判断
        if latest_data['close'] > latest_data['MA5'] > latest_data['MA20']:
            print("   📈 趋势: 上涨")
        elif latest_data['close'] < latest_data['MA5'] < latest_data['MA20']:
            print("   📉 趋势: 下跌")
        else:
            print("   📊 趋势: 震荡")


if __name__ == "__main__":
    main()
